<template>
  <m-container class="inventory" bg="#fff">
    <m-navbar title="库存盘点" background="#fff" :z-index="9" :customBack="customBack" :autoBack="false">
      <in-work-scan slot="right" class="nav-right" @change="handleScan" scan :validate="validate">
        <image src="@/static/icon11.png" mode="scaleToFill" class="img" />
        扫描托盘码
      </in-work-scan>
    </m-navbar>
    <view class="sticky-box">
      <view class="df aic jcsb">
        <m-cell
          is-link
          :title="imsList.map[map['imsList'].value] || '请选择仓库'"
          size="xs"
          :title-color="first && imsList.map[map['imsList'].value] ? '#248DFA' : ''"
          :round-radius="0"
          @click="handleStartSelect('imsList')"
        />
        <view class="line" />
        <m-cell
          is-link
          :title="wharfList.map[map['wharfList'].value] || '请选择码头'"
          :title-color="wharfList.map[map['wharfList'].value] ? '#248DFA' : ''"
          size="xs"
          :round-radius="0"
          @click="handleStartSelect('wharfList')"
        />

        <inventory-lock
          :wharfId="map['wharfList'].value"
          :wharfCode="wharfList.map[map['wharfList'].value]"
          :validate="validate"
          v-model="lock"
          @initWharfId="handleInitWharfId"
        />
      </view>
      <view class="df aic jcsb">
        <m-cell
          is-link
          :title="skuList.map[map['skuList'].value] || '请选择SKU'"
          :title-color="skuList.map[map['skuList'].value] ? '#248DFA' : ''"
          size="xs"
          :round-radius="0"
          @click="handleClick('skuList')"
        />
        <m-cell
          is-link
          :title="dicts['vmi_status'].map[map['vmiStatus'].value] || '请选择VMI状态'"
          :title-color="dicts['vmi_status'].map[map['vmiStatus'].value] ? '#248DFA' : ''"
          size="xs"
          :round-radius="0"
          @click="handleClick('vmiStatus')"
        />
      </view>
    </view>

    <view class="checkbox-box" v-if="list.length">
      <view
        class="checkbox"
        :class="{ active: getIsActive(it) }"
        v-for="it in list"
        :key="it.id + '_' + it.stackNo + '-' + it.levelNo + '-' + it.locationNo"
        @click="handleClickCheckbox(it)"
      >
        <text class="text">{{ it.stackNo + '-' + it.levelNo + '-' + it.locationNo }}</text>
        <text class="tag">{{ dicts['stock_status'].map[it.status] }}</text>
        <text class="status" :class="{ active: it.inventoryStatus === 1 }">{{
          inventoryStatusMap[it.inventoryStatus]
        }}</text>
      </view>
    </view>
    <m-empty v-else :margin-top="300" />

    <in-work-select-dict-popup
      :visible.sync="visible"
      :title="map[current].title"
      v-model="selectValue"
      :options="getOptions"
      @confirm="handleConfirm"
    />
    <inventory-switch v-model="switchConfig" v-if="getShowSwitch" />

    <m-fixed>
      <view class="footer">
        <inventory-switch v-model="switchConfig" modal="switch" ref="switch" />
        <m-button size="xl" @click="handleClickNext" width="80%" :loading="loading" :disabled="getDisabled">
          开始盘点
        </m-button>
      </view>
    </m-fixed>
  </m-container>
</template>

<script>
import { mapState } from 'vuex'
import { router } from '@/router'
import { showModal } from '@/hooks'
import { imsStockList, imsStockOutWorkAdd, palletCodeSkuList } from '@/api/modules/inventory'
import { wharfList, getImsInventoryPlan } from '@/api/modules/in-work'
import { getData, getMap } from '@/utils/index'
import { minCache } from '@/utils/min-cache'

export default {
  data() {
    return {
      value: [],
      visible: false,
      current: 'imsList',
      list: [],
      wharfList: {
        arr: [],
        map: {},
      },
      map: {
        imsList: {
          title: '选择仓库',
          value: '',
        },
        wharfList: {
          title: '选择码头',
          value: '',
        },
        skuList: {
          title: '选择SKU',
          value: '',
        },
        vmiStatus: {
          title: '请选择',
          value: '',
        },
      },
      inventoryStatusMap: {
        0: '未盘',
        1: '已盘',
      },
      switchConfig: 1,
      loading: false,
      first: false,
      selectValue: '',
      showPage: false,
      lock: false,
    }
  },
  computed: {
    ...mapState({
      imsList: (state) => state.cache.imsList,
      skuList: (state) => state.cache.skuList,
      dicts: (state) => state.outWork.dicts,
    }),
    getOptions() {
      if (['skuList'].includes(this.current)) {
        return [{ label: '全部', value: null }, ...this[this.current].arr]
      } else if (['wharfList'].includes(this.current)) {
        return [{ label: '全部', value: null }, ...this[this.current].arr]
      } else if (['vmiStatus'].includes(this.current)) {
        return [{ label: '全部', value: null }, ...this.dicts['vmi_status'].arr]
      }
      return this[this.current].arr
    },
    getDisabled() {
      return this.value.length === 0 || this.loading
    },
    getShowSwitch() {
      return !minCache.get('firstInventorySwitch') && this.switchConfig === 0
    },
    getIsActive() {
      return (it) => this.value.includes(it.id)
    },
  },
  onUnload() {
    uni.$off('clear')
    this.switchConfig = 1
    this.showPage = false
    this.$refs.switch.fetchData()
  },
  async onLoad() {
    this.showPage = true
    this.map.imsList.value = this.imsList.arr[0].value
    this.fetchData()
    uni.$on('clear', () => {
      this.value = []
    })
    const res = await getImsInventoryPlan({
      status: 2,
    })

    if (!res.data) {
      showModal({
        title: '温馨提示',
        content: '当前不存在正在执行的盘点计划，请创建盘点计划',
        showCancelButton: false,
        confirmText: '我知道了',
        slot: true,
        confirm: () => {
          uni.navigateBack({
            delta: 1,
          })
        },
      })
    }
    // this.handleScan('WMS-P-000039')
  },
  onShow() {
    this.fetchData()
  },
  onBackPress(e) {
    return this.customBack(true)
  },
  methods: {
    handleInitWharfId({ id, code }) {
      this.map['wharfList'].value = id
      this.wharfList.map[`${id}`] = code
    },
    handleStartSelect(e) {
      if (this.lock) {
        uni.showToast({
          title: '锁定之后禁止切换！',
          icon: 'none',
        })
        return
      }
      this.current = e
      this.selectValue = this.map[e].value || null
      this.visible = true
    },
    handleClickCheckbox({ imsId, levelNo, stackNo }) {
      this.value = this.list
        .filter((item) => `${imsId}-${levelNo}-${stackNo}` === `${item.imsId}-${item.levelNo}-${item.stackNo}`)
        .map((item) => item.id)
    },
    customBack(e) {
      if (this.switchConfig === 0) {
        e !== true && router.back(1)
        return false
      }

      showModal({
        title: '温馨提示',
        content: '请关闭手动控制!',
        showCancelButton: true,
        confirm: () => {
          this.$refs.switch.close(this.goBack)
        },
        cancel: () => {},
      })

      return true
    },
    async goBack() {
      this.$Router.$lockStatus = false
      uni.navigateBack({
        delta: 1,
      })
    },
    async handleScan(palletCode) {
      if (this.$Router.currentRoute.name !== 'Inventory') {
        return
      }

      if (palletCode.startsWith('WMS-P-')) {
        const { rows } = await palletCodeSkuList({
          status: 4,
          palletCode,
          pageNum: 1,
          pageSize: 10000,
        })

        if (rows.length === 0) {
          uni.showToast({
            title: '已出库的托盘中，不存在扫描的托盘码!',
            icon: 'none',
          })
          return
        }
        router.push({
          name: 'StartInventory',
          params: {
            palletCode,
          },
        })
      } else {
        uni.showToast({
          title: '请扫描正确的托盘码',
          icon: 'none',
        })
      }
    },
    async validate() {
      if (!this.showPage) {
        return false
      }

      this.$refs.switch.fetchData()

      if (this.switchConfig === 0 && this.$Router.currentRoute.name === 'Inventory') {
        uni.showToast({
          title: '请先开启手动控制',
          icon: 'none',
        })
        return false
      }
      return true
    },
    async handleClick(e) {
      if (await this.validate()) {
        this.current = e
        this.selectValue = this.map[e].value || null
        this.visible = true
        this.value = []
      }
    },
    async handleClickNext() {
      if (!(await this.validate())) {
        return
      }

      if (!this.lock) {
        uni.showToast({
          title: '请锁定码头',
          icon: 'none',
        })
        return
      }

      const wharfId = this.map['wharfList'].value
      const vmiStatus = this.map['vmiStatus'].value

      if (wharfId === '') {
        uni.showToast({
          title: '请选择码头',
          icon: 'none',
        })
        return
      }

      const current = this.list.filter((item) => this.value.includes(item.id))
      const { imsId, levelNo, stackNo } = current[0] || {}

      this.loading = true
      try {
        const { data } = await imsStockOutWorkAdd({
          wharfId,
          imsId,
          levelNo,
          stackNo,
          type: 1,
          vmiStatus,
        })
        router.push({
          name: 'StartInventory',
          params: {
            id: data,
            deliveryStartCode: this.imsList.map[wharfId],
          },
        })
      } catch (e) {}
      this.loading = false
    },
    async fetchData() {
      const imsId = this.map['imsList'].value
      const { data } = await imsStockList({
        imsId,
        skuId: this.map['skuList'].value,
        vmiStatus: this.map['vmiStatus'].value,
      })
      this.list = data.map((item) => item.imsStocks).flat(1)

      if (this.current === 'imsList') {
        const { rows } = await wharfList({
          imsId,
          pageNum: 1,
          pageSize: 10000,
          workStatus: 0,
          type: 2,
        })

        const arr = getData(rows, 'wharfCode', 'wharfId')
        this.wharfList = {
          arr,
          map: {
            ...this.wharfList.map,
            ...getMap(arr),
          },
        }
      }
    },
    async handleConfirm(e) {
      if ('imsList' === this.current) {
        this.first = true
      }

      this.map[this.current].value = e
      if (['imsList', 'skuList', 'vmiStatus'].includes(this.current)) {
        this.fetchData()
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.inventory {
  .nav-right {
    color: #248dfa;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    margin: 0;
    .img {
      width: 49rpx;
      height: 49rpx;
      margin-right: 10rpx;
    }
  }
  .sticky-box {
    background-color: #fff;
    box-shadow: 0px 8px 13px 0px rgba(200, 208, 217, 0.42);
  }
  .cell {
    margin: 0;
    flex: 1;
  }
  .jcsb {
    border-bottom: 1rpx solid #dfe5eb;
  }
  .line {
    background: #dfe5eb;
    width: 1rpx;
    height: 60rpx;
    overflow: hidden;
  }
  .checkbox-box {
    display: grid;
    grid-template-columns: repeat(4, 160rpx);
    grid-gap: 20rpx;
    padding: 20rpx;

    .tag {
      background: RGBA(220, 234, 248, 1);
      color: #248dfa;
      font-size: 22rpx;
      position: absolute;
      top: 0;
      left: 0;
      border-radius: 8rpx 0rpx 8rpx 0rpx;
      text-align: center;
      padding: 5rpx 8rpx;
    }

    .status {
      font-size: 22rpx;
      display: block;
      color: #14567f;
      margin-top: 4rpx;
      &.active {
        color: #1cd68e;
      }
    }

    .checkbox {
      margin: 0;
      background: #f5f7f8;
      position: relative;
      padding: 40rpx 0 15rpx;
      font-size: 30rpx;
      font-weight: bold;
      text-align: center;
      border-radius: 8rpx;
      &.active {
        border: 1rpx solid #248dfa;
      }
    }
  }
  .footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
